package indi.jp.project.business.pub.service.impl;

import indi.jp.project.business.pub.dao.ProjectDAO;
import indi.jp.project.business.pub.pojo.ProjectStatusEnum;
import indi.jp.project.business.pub.pojo.po.ProjectPO;
import indi.jp.project.business.pub.pojo.query.ProjectQuery;
import indi.jp.project.core.entity.Datagrid;
import indi.jp.project.core.entity.JsonResult;
import indi.jp.project.business.pub.service.ProjectService;
import indi.jp.project.core.util.SerialUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class ProjectServiceImpl implements ProjectService {

    @Resource
    private ProjectDAO projectDAO;

    @Resource
    private SerialUtil serialUtil;

    @Override
    public JsonResult queryGrid(ProjectQuery query) throws Exception {
        List<ProjectPO> list = projectDAO.queryList(query);
        int count = projectDAO.queryCount(query);
        Datagrid<ProjectPO> datagrid = new Datagrid<>(list, count);
        return JsonResult.success(datagrid);
    }

    @Override
    public JsonResult save(ProjectPO projectPO) throws Exception {
        projectPO.setStatusName(ProjectStatusEnum.valueOf(projectPO.getStatus()).getName());
        if (StringUtils.isBlank(projectPO.getId())) {
            String id = String.valueOf(serialUtil.nextId());
            projectPO.setId(id);
            projectDAO.insert(projectPO);
        } else {
            projectDAO.update(projectPO);
        }
        return JsonResult.success();
    }

    @Override
    public JsonResult deleteById(String id) throws Exception {
        projectDAO.deleteById(id);
        return JsonResult.success();
    }

    @Override
    public JsonResult findById(String id) throws Exception {
        ProjectPO project = projectDAO.findById(id);
        return JsonResult.success(project);
    }

    @Override
    public String add(ProjectPO projectPO) throws Exception {
        String id = String.valueOf(serialUtil.nextId());
        projectPO.setId(id);
        projectDAO.insert(projectPO);
        return id;
    }

    @Override
    public void edit(ProjectPO projectPO) throws Exception {
        projectDAO.update(projectPO);
    }
}
